import React, { Component } from 'react'
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import ImgCrop from 'antd-img-crop';

import { ServerURL, UploadAvatarURL } from '../../utils/config'
import { setLocalStorage, getLocalStorage } from '../../utils/utils'



function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('你必须上传jpg/png格式文件');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片文件大小不要超过2M!');
    }
    return isJpgOrPng && isLt2M;
}

export default class UploadAvatar extends Component {
    state = {
        loading: false,
        imageUrl: this.props.avatarUrl
    };
    handleChange = info => {
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done') {
            let { url } = info.file.response
            this.setState({
                imageUrl: url,
                loading: false
            })
            let userInfo = JSON.parse(getLocalStorage('userInfo'))
            userInfo.avatarUrl = url
            setLocalStorage('userInfo', JSON.stringify(userInfo))
            message.destroy()
            message.success({ content: info.file.response.msg, duration: 2 })

        }
    };
    render() {
        const uploadButton = (
            <div>
                {this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div className="ant-upload-text">上传头像</div>
            </div>
        );
        const props = {
            aspect: 100 / 100,  //裁剪宽度
            grid: true,
            rotate: true,
            modalTitle: "编辑头像",
            modalOk: "确定",
            modalCancel: "取消",
        }
        const { imageUrl } = this.state;
        return (
            <ImgCrop  {...props}>
                <Upload
                    name="avatar"
                    listType="picture-card"
                    className="avatar-uploader"
                    data={{ account: this.props.account }}
                    showUploadList={false}
                    action={UploadAvatarURL}
                    beforeUpload={beforeUpload}
                    onChange={this.handleChange}>
                    {imageUrl ? <img src={ServerURL + imageUrl} alt="avatar" style={{ height: '100px' }} /> : uploadButton}
                </Upload>
            </ImgCrop >
        );
    }
}


